<!--
 * @Descripttion: 
 * @version: 
 * @Author: 尹鹏孝
 * @Date: 2021-12-10 09:37:44
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2021-12-10 09:46:07
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>二叉树的节点平均值</title>
</head>

<body>
    <script>
        // 给定一个非空二叉树, 返回一个由每层节点平均值组成的数组。
        // 思路：本层级别的求和然后求平均值，然后输出

        class Node {
            constructor(root, left, right) {
                this.root = root;
                this.left = left;
                this.right = right;
            }
            averageOfLevels(root) {
                // 平均值
                let res = [], queue = [];
                queue.push(root);
                while (queue.length && root !== null) {
                    // 每个层级节点数
                    let length = queue.length;
                    // sum求每一层的和
                    let sum = 0;
                    for (let i = 0; i < length; i++) {
                        let node = queue.shift();
                        sum += node.root;
                        node.left && queue.push(node.left);
                        node.right && queue.push(node.right);
                    }
                    // 每一层的平均值存入数组res  
                    res.push(sum / length);
                }
            }
        }




    </script>
</body>

</html>